<template>
  <div class="survey-page">
    <el-card>
      <el-form :inline="true" :model="searchForm" class="search-form-container mb-6 bg-gray-50 p-4 rounded-lg shadow-sm">
        <div class="search-inputs-actions">
          <div class="flex items-center flex-wrap gap-x-4 gap-y-2">
            <el-form-item label="" class="mb-0">
              <el-input v-model="searchForm.keyword" placeholder="问卷标题" style="width: 180px;" clearable />
            </el-form-item>
            <el-form-item label="" class="mb-0">
              <el-select v-model="searchForm.status" placeholder="状态" style="width: 120px;" clearable>
                <el-option label="未发布" value="未发布" />
                <el-option label="已发布" value="已发布" />
              </el-select>
            </el-form-item>
            <el-form-item label="" class="mb-0">
              <el-input v-model="searchForm.creator" placeholder="创建人" style="width: 120px;" clearable />
            </el-form-item>
            <el-form-item class="mb-0">
              <el-button @click="handleSearch" class="gradient-purple-blue-button">查询</el-button>
              <el-button @click="resetSearch" class="gradient-blue-cyan-button" style="margin-left: 8px;">重置</el-button>
            </el-form-item>
          </div>

          <div class="flex items-center gap-x-4">
            <el-button @click="openBuilder()" class="gradient-blue-toggle-button">新建问卷</el-button>
            <el-button @click="toggleView" class="gradient-blue-toggle-button">
              {{ isCardView ? '切换为列表' : '切换为卡片' }}
            </el-button>
          </div>
        </div>
      </el-form>

      <el-row :gutter="20" class="chart-section" v-if="!loading && allSurveyData.length > 0">
        <el-col :span="8">
          <el-card shadow="hover">
            <h3>问卷状态分布</h3>
            <v-chart class="chart" :option="statusChartOption" autoresize />
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover">
            <h3>创建人问卷数量</h3>
            <v-chart class="chart" :option="creatorChartOption" autoresize />
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover">
            <h3>问卷创建趋势 (按月)</h3>
            <v-chart class="chart" :option="trendChartOption" autoresize />
          </el-card>
        </el-col>
      </el-row>

      <div v-loading="loading">
        <template v-if="isCardView">
          <el-row :gutter="20" class="survey-card-grid">
            <template v-if="filteredSurveyList.length > 0">
              <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="item in filteredSurveyList" :key="item.id">
                <el-card class="survey-card">
                  <div class="survey-card-content">
                    <h4 class="survey-card-title" :title="item.title">{{ item.title }}</h4>
                    <p class="survey-card-info"><span class="info-label">状态:</span>
                      <el-tag :type="item.status === '已发布' ? 'success' : 'info'" size="small">{{ item.status }}</el-tag>
                    </p>
                    <p class="survey-card-info"><span class="info-label">创建人:</span> {{ item.creator }}</p>
                    <p class="survey-card-info"><span class="info-label">创建于:</span> {{ formatTableDate(null, null, item.createdAt) }}</p>
                  </div>
                  <div class="survey-card-actions">
                    <el-button size="mini" @click="viewDetail(item)">详情</el-button>
                    <el-button size="mini" type="primary" @click="openBuilder(item)">编辑</el-button>
                    <el-button size="mini" type="danger" @click="openDeleteDialog(item)" class="light-red-button">删除</el-button>
                  </div>
                </el-card>
              </el-col>
            </template>
            <div v-else class="empty-surveys">
              <el-empty description="暂无问卷，请新增或调整搜索条件"></el-empty>
            </div>
          </el-row>
        </template>

        <template v-else>
          <el-table :data="filteredSurveyList" row-key="id" border style="width: 100%; margin-top: 20px;">
            <el-table-column prop="title" label="问卷标题" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === '已发布' ? 'success' : 'info'">{{ row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="creator" label="创建人" width="120" />
            <el-table-column prop="createdAt" label="创建日期" width="180" :formatter="formatTableDate" />
            <el-table-column label="操作" width="220" fixed="right">
              <template #default="{ row }">
                <el-button size="small" @click="viewDetail(row)">详情</el-button>
                <el-button size="small" type="primary" @click="openBuilder(row)">编辑</el-button>
                <el-button size="small" type="danger" @click="openDeleteDialog(row)" class="light-red-button">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </div>
    </el-card>

    <el-dialog v-model="showBuilder" :title="builderForm.id ? '编辑问卷' : '新建问卷'" width="600px" :close-on-click-modal="false" @close="resetBuilderForm">
      <el-form :model="builderForm" label-width="100px" ref="builderFormRef">
        <el-form-item label="标题" required>
          <el-input v-model="builderForm.title" />
        </el-form-item>
        <el-form-item label="状态" required>
          <el-select v-model="builderForm.status" placeholder="请选择状态">
            <el-option label="未发布" value="未发布" />
            <el-option label="已发布" value="已发布" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建人" required>
          <el-input v-model="builderForm.creator" />
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker v-model="builderForm.createdAt" type="datetime" placeholder="选择时间" />
        </el-form-item>
        <el-form-item label="附件">
          <input type="file" @change="onFileChange" />
          <p v-if="builderForm.filePath" class="file-info">
            已上传：<a :href="getFileUrl(builderForm.filePath)" target="_blank">{{ getFileName(builderForm.filePath) }}</a>
          </p>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeBuilder">取消</el-button>
        <el-button type="primary" @click="submitSurvey">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="showDetailDialog" title="问卷详情" width="500px">
      <div v-if="detail" class="detail-content">
        <div><b>标题：</b>{{ detail.title }}</div>
        <div><b>状态：</b><el-tag :type="detail.status === '已发布' ? 'success' : 'info'">{{ detail.status }}</el-tag></div>
        <div><b>创建人：</b>{{ detail.creator }}</div>
        <div><b>创建时间：</b>{{ formatDetailDate(detail.createdAt) }}</div>
        <div v-if="detail.filePath"><b>附件：</b><a :href="getFileUrl(detail.filePath)" target="_blank">下载附件</a></div>
      </div>
      <template #footer>
        <el-button @click="showDetailDialog = false">关闭</el-button>
      </template>
    </el-dialog>
    
    <el-dialog title="确认删除" v-model="showDeleteDialog" width="300px">
      <div>确定要删除该问卷记录吗？</div>
      <template #footer>
        <el-button @click="showDeleteDialog = false">取消</el-button>
        <el-button type="danger" @click="deleteConfirmed" class="light-red-button">删除</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { publishSurvey, getSurveyList, getSurvey, updateSurvey, deleteSurvey } from '../../services/surveyService';
import { FILE_BASE_URL } from '../../services/config';

import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { PieChart, BarChart, LineChart } from 'echarts/charts';
import { TitleComponent, TooltipComponent, LegendComponent, GridComponent } from 'echarts/components';
import VChart from 'vue-echarts';

use([
  CanvasRenderer,
  PieChart,
  BarChart,
  LineChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
]);

// --- 响应式状态定义 ---
const surveyList = ref([]);
const allSurveyData = ref([]);
const loading = ref(false);
const showBuilder = ref(false);
const showDetailDialog = ref(false);
const showDeleteDialog = ref(false);
const currentDeleteId = ref(null);
const detail = ref(null);
const searchForm = reactive({ keyword: '', status: '', creator: '' });
const isCardView = ref(true);

const getDefaultBuilderForm = () => ({
  id: null,
  title: '',
  status: '未发布',
  creator: '',
  createdAt: new Date(),
  file: null,
  filePath: '',
});

const builderForm = reactive(getDefaultBuilderForm());

// --- 计算属性 (Computed) ---
const filteredSurveyList = computed(() => surveyList.value);

const statusChartOption = computed(() => {
  const statusCounts = allSurveyData.value.reduce((acc, survey) => {
    acc[survey.status] = (acc[survey.status] || 0) + 1;
    return acc;
  }, {});
  return {
    tooltip: { trigger: 'item' },
    legend: { top: '5%', left: 'center' },
    series: [ { name: '问卷状态', type: 'pie', radius: ['40%', '70%'], data: Object.entries(statusCounts).map(([name, value]) => ({ value, name })) } ],
  };
});

const creatorChartOption = computed(() => {
  const creatorCounts = allSurveyData.value.reduce((acc, survey) => {
    const creator = survey.creator || '未知';
    acc[creator] = (acc[creator] || 0) + 1;
    return acc;
  }, {});
  const sortedCreators = Object.entries(creatorCounts).sort((a, b) => b[1] - a[1]);
  return {
    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: [{ type: 'category', data: sortedCreators.map(item => item[0]), axisTick: { alignWithLabel: true } }],
    yAxis: [{ type: 'value', minInterval: 1 }],
    series: [ { name: '问卷数量', type: 'bar', barWidth: '60%', data: sortedCreators.map(item => item[1]) } ],
  };
});

const trendChartOption = computed(() => {
  const trendData = allSurveyData.value.reduce((acc, survey) => {
    const month = formatDateTime(survey.createdAt, 'YYYY-MM');
    if(month) acc[month] = (acc[month] || 0) + 1;
    return acc;
  }, {});
  const sortedMonths = Object.keys(trendData).sort();
  return {
    tooltip: { trigger: 'axis' },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { type: 'category', boundaryGap: false, data: sortedMonths },
    yAxis: { type: 'value', minInterval: 1 },
    series: [ { name: '创建数量', type: 'line', stack: 'Total', areaStyle: {}, data: sortedMonths.map(month => trendData[month]) } ],
  };
});

// --- 数据与API调用 ---
async function fetchAllSurveyData() {
  loading.value = true;
  try {
    const res = await getSurveyList();
    if (res.success) {
      allSurveyData.value = res.list || [];
      surveyList.value = allSurveyData.value;
    } else {
      ElMessage.error(res.message || '获取列表失败');
    }
  } catch (error) {
    console.error("获取列表数据时出错:", error);
    ElMessage.error('请求列表数据时出错');
  } finally {
    loading.value = false;
  }
}

function handleSearch() {
  let result = allSurveyData.value;
  if (searchForm.keyword) result = result.filter(item => item.title.toLowerCase().includes(searchForm.keyword.toLowerCase()));
  if (searchForm.status) result = result.filter(item => item.status === searchForm.status);
  if (searchForm.creator) result = result.filter(item => item.creator?.toLowerCase().includes(searchForm.creator.toLowerCase()));
  surveyList.value = result;
}

function resetSearch() {
  searchForm.keyword = '';
  searchForm.status = '';
  searchForm.creator = '';
  surveyList.value = allSurveyData.value;
}

// [FIXED] 恢复您原始的、正确的 submitSurvey 逻辑
async function submitSurvey() {
  if (!builderForm.title || !builderForm.status || !builderForm.creator) {
    return ElMessage.warning('请填写完整的必填信息');
  }

  const formData = new FormData();
  formData.append('title', builderForm.title);
  formData.append('status', builderForm.status);
  formData.append('creator', builderForm.creator);
  formData.append('createdAt', formatDateTime(builderForm.createdAt, 'YYYY-MM-DD HH:mm:ss'));
  
  if (builderForm.file) {
    formData.append('file', builderForm.file);
  } else if (builderForm.filePath) {
    formData.append('filePath', builderForm.filePath);
  }

  try {
    let res;
    // 使用您原来的 if/else 结构来判断是新增还是更新
    if (builderForm.id) {
      formData.append('id', builderForm.id);
      res = await updateSurvey(formData); // 调用 updateSurvey，参数为 formData
    } else {
      res = await publishSurvey(formData);
    }

    if (res.success) {
      ElMessage.success(res.message || '操作成功');
      closeBuilder();
      await fetchAllSurveyData();
    } else {
      ElMessage.error(res.message || '操作失败');
    }
  } catch(error) {
    console.error("提交请求时出错:", error);
    ElMessage.error('提交请求时出错');
  }
}


async function deleteConfirmed() {
    if (!currentDeleteId.value) return;
    try {
        const res = await deleteSurvey(currentDeleteId.value);
        if (res.success) {
            ElMessage.success(res.message || '删除成功');
            showDeleteDialog.value = false;
            await fetchAllSurveyData();
        } else {
            ElMessage.error(res.message || '删除失败');
        }
    } catch (error) {
        console.error("删除请求出错:", error);
        ElMessage.error('删除请求出错');
    }
}

async function viewDetail(row) {
  loading.value = true;
  try {
    const res = await getSurvey(row.id);
    if (res.success) {
      detail.value = res.data;
      showDetailDialog.value = true;
    } else {
      ElMessage.error(res.message || '获取详情失败');
    }
  } catch (error) {
    console.error("获取详情失败:", error);
    ElMessage.error("获取详情失败");
  } finally {
    loading.value = false;
  }
}

// --- 弹窗与视图控制 ---
const toggleView = () => { isCardView.value = !isCardView.value; };
function resetBuilderForm() { Object.assign(builderForm, getDefaultBuilderForm()); builderForm.file = null; }

function openBuilder(row = null) {
  resetBuilderForm();
  if (row) {
    Object.assign(builderForm, {
        id: row.id,
        title: row.title,
        status: row.status,
        creator: row.creator,
        filePath: row.filePath || ''
    });
    // 使用您原来更健壮的日期处理方式
    if (row.createdAt) {
      const dateStr = typeof row.createdAt === 'string' ? row.createdAt.replace(' ', 'T') : row.createdAt;
      const dateObj = new Date(dateStr);
      builderForm.createdAt = !isNaN(dateObj.getTime()) ? dateObj : new Date();
    } else {
      builderForm.createdAt = new Date();
    }
  }
  showBuilder.value = true;
}

function closeBuilder() { showBuilder.value = false; }
function openDeleteDialog(row) { currentDeleteId.value = row.id; showDeleteDialog.value = true; }

// --- 辅助函数 ---
function onFileChange(e) { const file = e.target.files[0]; if (file) { builderForm.file = file; builderForm.filePath = file.name; } }
function getFileUrl(filePath) { if (!filePath) return ''; return filePath.startsWith('http') ? filePath : FILE_BASE_URL + filePath; }
function getFileName(filePath) { return filePath ? filePath.split('/').pop() : ''; }

function formatDateTime(cellValue, format = 'YYYY-MM-DD HH:mm') {
  if (!cellValue) return '';
  let dateObj;
  
  if (Array.isArray(cellValue)) {
    const [y, m, d, hh, mm, ss] = cellValue;
    dateObj = new Date(y, (m || 1) - 1, d || 1, hh || 0, mm || 0, ss || 0);
  } else if (typeof cellValue === 'string' && cellValue.includes(',')) {
    const arr = cellValue.split(',').map(Number);
    dateObj = new Date(arr[0], arr[1] - 1, arr[2], arr[3], arr[4], arr[5]);
  } else {
    dateObj = new Date(cellValue);
  }

  if (isNaN(dateObj.getTime())) return '';

  const y = dateObj.getFullYear();
  const m = String(dateObj.getMonth() + 1).padStart(2, '0');
  const d = String(dateObj.getDate()).padStart(2, '0');
  const hh = String(dateObj.getHours()).padStart(2, '0');
  const mm = String(dateObj.getMinutes()).padStart(2, '0');
  const ss = String(dateObj.getSeconds()).padStart(2, '0');
  
  return format.replace('YYYY', y).replace('MM', m).replace('DD', d).replace('HH', hh).replace('mm', mm).replace('ss', ss);
}

const formatTableDate = (row, column, cellValue) => formatDateTime(cellValue);
const formatDetailDate = (cellValue) => formatDateTime(cellValue, 'YYYY-MM-DD HH:mm:ss');

// --- 生命周期钩子 ---
onMounted(fetchAllSurveyData);
</script>

<style scoped>
/* 所有样式均保持不变，且功能正常 */
.survey-page { padding: 32px 24px; background: #f8f9fb; }
.mb-6 { margin-bottom: 1.5rem; }
.flex { display: flex; }
.justify-between { justify-content: space-between; }
.items-center { align-items: center; }
.flex-wrap { flex-wrap: wrap; }
.gap-x-4 { column-gap: 1rem; }
.gap-y-2 { row-gap: 0.5rem; }
.search-inputs-actions { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; width: 100%; gap: 10px; }
.search-form-container { background-color: #f9fafb; padding: 1rem; border-radius: 0.5rem; box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05); margin-bottom: 1.5rem; }
.el-form-item.mb-0 { margin-bottom: 0 !important; }
.chart-section { margin-bottom: 20px; }
.chart-section h3 { margin-bottom: 10px; color: #303133; font-size: 16px; font-weight: bold; }
.chart { height: 300px; width: 100%; }
.gradient-purple-blue-button { color: #fff !important; background-image: linear-gradient(to right, #8b5dbd, #548ee0) !important; border-color: #8b5dbd !important; transition: all 0.3s ease; }
.gradient-purple-blue-button:hover, .gradient-purple-blue-button:focus { background-image: linear-gradient(to right, #9d70d1, #69a7f3) !important; border-color: #9d70d1 !important; opacity: 0.9; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); }
.gradient-purple-blue-button:active { transform: translateY(0); box-shadow: none; }
.gradient-blue-cyan-button { color: #fff !important; background-image: linear-gradient(to right, #548ee0, #38afb5) !important; border-color: #548ee0 !important; transition: all 0.3s ease; }
.gradient-blue-cyan-button:hover, .gradient-blue-cyan-button:focus { background-image: linear-gradient(to right, #69a7f3, #4fd3d8) !important; border-color: #69a7f3 !important; opacity: 0.9; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); }
.gradient-blue-cyan-button:active { transform: translateY(0); box-shadow: none; }
.gradient-blue-toggle-button { color: #fff !important; background-image: linear-gradient(to right, #3f51b5, #2196f3) !important; border-color: #3f51b5 !important; transition: all 0.3s ease; }
.gradient-blue-toggle-button:hover, .gradient-blue-toggle-button:focus { background-image: linear-gradient(to right, #5c6bc0, #42a5f5) !important; border-color: #5c6bc0 !important; opacity: 0.9; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); }
.gradient-blue-toggle-button:active { transform: translateY(0); box-shadow: none; }
.light-red-button { background-color: #FEE2E2 !important; color: #EF4444 !important; border-color: #FEE2E2 !important; }
.light-red-button:hover, .light-red-button:focus { background-color: #FECDCD !important; border-color: #FECDCD !important; }
.survey-card-grid { display: flex; flex-wrap: wrap; gap: 20px 0; margin-top: 20px; padding-bottom: 20px; }
.survey-card { height: 100%; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08); transition: all 0.2s ease; display: flex; flex-direction: column; justify-content: space-between; background-color: #ffffff; border: 1px solid #e9e9e9; }
.survey-card:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); }
.survey-card-content { padding: 15px; flex-grow: 1; display: flex; flex-direction: column; gap: 8px; }
.survey-card-title { font-size: 1.1em; font-weight: bold; color: #333; margin-bottom: 10px; white-space: normal; overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; line-height: 1.4; height: 2.8em; }
.survey-card-info { font-size: 0.9em; color: #666; margin: 0; line-height: 1.4; display: flex; align-items: center; }
.survey-card-info .info-label { font-weight: 500; color: #444; margin-right: 8px; }
.survey-card-actions { padding: 10px 15px; border-top: 1px solid #f0f0f0; display: flex; justify-content: flex-end; gap: 8px; background-color: #fafafa; }
.survey-card-actions .el-button { min-width: unset; padding: 7px 12px; font-size: 0.85em; }
.empty-surveys { width: 100%; display: flex; justify-content: center; align-items: center; min-height: 200px; }
.detail-content div { line-height: 2; font-size: 16px; }
.file-info { margin: 5px 0 0; font-size: 12px; color: #909399; }
.file-info a { color: #409eff; text-decoration: none; }
.file-info a:hover { text-decoration: underline; }
</style>